/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import models.Quizquestion;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class QuizQuestionsDao {

    private final Session session;

    /*
     * constructor
     * parameter session
     */
    public QuizQuestionsDao(Session session) {
        this.session = session;
    }

    /*
     * Returns a list of all questions
     */
    public List<Quizquestion> findAll() {
        Transaction tx = session.beginTransaction();
        List<Quizquestion> list = session.createQuery("from Quizquestion").list();
        tx.commit();
        return list;
    }

    /*
     * Returns a list of all questions by quiz
     * parameter id = quiz id
     */
    public List<Quizquestion> findAllbyQuiz(long id) {
        Transaction tx = session.beginTransaction();
        List<Quizquestion> list = session.createQuery("from Quizquestion where quiz_quiz_id = " + id + " order by question_order").list();
        tx.commit();
        return list;
    }

    /*
     * Saves a question
     */
    public boolean save(Quizquestion question) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(question);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * Updates a question
     * returns true if updated
     */
    public boolean update(Quizquestion question) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(question);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * returns quiz
     * parameter id = question id
     */
    public Quizquestion get(long id) {
        return (Quizquestion) session.get(Quizquestion.class, id);
    }

    /*
     * Deletes question
     * parameter question = question object
     */
    public void delete(Quizquestion question) {
        Transaction tx = session.beginTransaction();
        session.delete(question);
        tx.commit();
    }

    /*
     * Returns list of answer by question
     * parameter id = question id
     */
    public List<Quizquestion> findAnswer(long id) {
        Transaction tx = session.beginTransaction();
        List<Quizquestion> list = session.createQuery("from Quiz_answer where question_question_id = " + id).list();
        tx.commit();
        return list;
    }
}
